package memorphic.simpleloginsample.views
{
	import memorphic.simpleloginsample.ISampleAppContext;
	import memorphic.simpleloginsample.model.LoginStatus;
	import memorphic.slide.SlidePresModelBase;
	import memorphic.slide.slide_private;

	public class LoginViewPresModel extends SlidePresModelBase
	{
		
		// N.B. These constants should be externalised in a resource bundle
		public static const WELCOME_MSG:String = "Please log in to continue, or register if you do not have an account already.";
		public static const REGISTER_MSG:String = "To register, please choose a user name and password. Type the password again so we can check for typing errors";
		public static const AUTHENTICATING_MSG:String = "Authenticating...";
		public static const REGISTERING_MSG:String = "Registering...";
		
		use namespace slide_private;

		[Bindable]
		public var context:ISampleAppContext;
		
		
		
		[Bindable]
		public var welcomeText:String = WELCOME_MSG;
		
		
		[Bindable]
		public var registerText:String = REGISTER_MSG;
		
		
		
		[Bindable]
		public var statusText:String = "";
		
		private var errorText:String = "";
		
		
		[Bindable]
		public var isLoginError:Boolean;
		
		
		
		[Bindable]
		[Trigger(path="context.session.userName")]
		public var previousLoginName:String;
		
		
		[Trigger(path="context.session.error")]
		slide_private function onLoginErrorChange(error:String):void
		{
			errorText = error;
			if(error){
				isLoginError = true;
				statusText = errorText;
			}else{
				isLoginError = false;
			}
		}
				
		[Trigger(path="context.session.status")]
		slide_private function onLoginStatusChange(status:String):void
		{
			if(status == LoginStatus.AUTHENTICATING){
				statusText = AUTHENTICATING_MSG;
			}else if(status == LoginStatus.REGISTERING){
				statusText = REGISTERING_MSG;
			}else if(isLoginError){
				statusText = errorText;
			}else{
				statusText = "";
			}
		}
		
		public function LoginViewPresModel(view:ISampleAppContext)
		{
			super(view);
			context = view;
		}
		
		
		
		protected override function initView():void
		{
		}
		
		
		public function submitLogin(name:String, pass:String):void
		{
			resetStatus();
			context.loginController.submitLogin(name, pass);
		}
		
		
		public function submitRegistration(name:String, pass:String, passConfirm:String):void
		{
			resetStatus();
			context.loginController.submitRegistration(name, pass, passConfirm);
		}
		
		
		public function showRegistration():void
		{
			resetStatus();
			context.loginController.showRegistration();
		}
		
		
		public function showLogin():void
		{
			resetStatus();
			context.loginController.showLogin();
		}
		
		
		private function resetStatus():void
		{
			statusText = "";
			errorText = "";
			isLoginError = false;
		}
	}
}